import {
    PlayerLevelConfigs,
} from "db://assets/proto/shared/v1/configs";
import {GlobalConfigsLoader} from "db://assets/script/global-configs-loader";
import Long from "long";
import {cmm} from "db://assets/script/utils/cmm";

export class PlayerConfigsLoader {

    private _buildingNumLimit: Map<number, number> | null = null;
    private _buildingLevelLimit: Map<number, number> | null = null;
    private _playerLevelConfigs: PlayerLevelConfigs[] | null = null;


    findPlayerLevelConfigsByExp(exp: Long): PlayerLevelConfigs | undefined {
        const flc = GlobalConfigsLoader.instance.getPlayerLevelConfigs()
        if (!this._playerLevelConfigs) {
            this._playerLevelConfigs = cmm.map2array(flc, (k, v) => v)
        }
        const level = this._playerLevelConfigs.filter((item) => item.requireExp.lte(exp)).length
        return flc.get(level.toString())
    }


    findPlayerLevelByExp(exp: Long): number {
        if (!this._playerLevelConfigs) {
            const flc = GlobalConfigsLoader.instance.getPlayerLevelConfigs()
            this._playerLevelConfigs = cmm.map2array(flc, (k, v) => v)
        }
        return this._playerLevelConfigs.filter((item) => item.requireExp.lte(exp)).length
    }


    findPlayerLevelConfigsByLevel(level: number): PlayerLevelConfigs | undefined {
        const flc = GlobalConfigsLoader.instance.getPlayerLevelConfigs()
        return flc.get(level.toString())
    }

    findBuildingNumLimitConfigsByLevel(level: number, buildingId: Long): number | undefined {
        if (!this._buildingNumLimit) {
            const pc = this.findPlayerLevelConfigsByLevel(level)
            if (!pc) return undefined
            this._buildingNumLimit = cmm.entriesKeys(pc.buildingNumLimit, (k, v) => k.toNumber())
        }
        return this._buildingNumLimit.get(buildingId.toNumber())
    }

    findBuildingLevelLimitConfigsByLevel(level: number, buildingId: Long): number | undefined {
        if (!this._buildingLevelLimit) {
            const pc = this.findPlayerLevelConfigsByLevel(level)
            if (!pc) return undefined
            this._buildingLevelLimit = cmm.entriesKeys(pc.buildingLevelLimit, (k, v) => k.toNumber())
        }
        return this._buildingLevelLimit.get(buildingId.toNumber())
    }

}

export const playerConfigsLoader = new PlayerConfigsLoader();